﻿using System;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Filters;

namespace Aecg.OwinSelfHostServer.Service
{
    public class ErrorFilterAttribute : IExceptionFilter
    {
        public bool HasWrappedFilter => WrappedFilter != null;

        public IExceptionFilter WrappedFilter { get; set; }

        public bool AllowMultiple => HasWrappedFilter && WrappedFilter.AllowMultiple;

        public Task ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext,
            CancellationToken cancellationToken)
        {
            if (actionExecutedContext == null)
                throw new ArgumentNullException("actionExecutedContext");

            OnHttpException(actionExecutedContext, cancellationToken);
            return Task.FromResult(0);
        }

        public virtual void OnHttpException(HttpActionExecutedContext actionExecutedContext,
            CancellationToken cancellationToken)
        {
            if (HasWrappedFilter)
                WrappedFilter.ExecuteExceptionFilterAsync(actionExecutedContext, cancellationToken);
            //todo 日志处理
        }
    }
}